Learn Regular Expressions (RegExp)
Defining the string in which we have to search the regExp.

let string = "Hello there, I am Abhishek Kumar. I hope you are fine there.";
            
Defining the regex directly, and printing it source value.

let regDirect = /I/;
console.log(regDirect.source);
            

I
            
Defining a regex using its constructor function.

const toFind = 'I';
let regConstructor = new RegExp(toFind);
console.log(regConstructor);
            

/I/
            
The test() function returns true if the given regex is present in the string passed to

const isPresent = regDirect.test(string);
console.log(isPresent);
            

true
            
In the given way we can check for multiple items i.e the function will returns true if any one of the regex matches in the string passed to it.

let petString = 'Abhishek has a pet cat.';
let petRegex = /cat|dog|mouse|/;
let result = petRegex.test(petString);
console.log(result);
            

true
            
If we want to ignore case then we have to add a flag i after our regex;

let newString = 'ThIs Is tO test The case InsenstIVity';  
let caseRegex = /this/i;
let result = caseRegex.test(newString);
console.log(result);              
            

true
            
Adding the flags using the constructor function

let searchTerm = 'this';
let regex = new RegExp(searchTerm, 'i');
            
There comes an another function match() that is applied on a string and a regex is passed to it as an argument, and it will returns the first match it found or (all matches if flag applied is global) in the string, else it returns null.

let extractString = "Hey there, Extract the word 'hello' hello from the string";
let extractRegex = new RegExp('hello');
let output = extractString.match(extractRegex);
console.log(output);
            

[
    'hello',
    index: 29,
    input: "Hey there, Extract the word 'hello' from the string",
    groups: undefined
]
            
If we add flag g then it returs an array of matches it found.

let extractString = "Hey there, Extract the word 'hello' hello from the string";
let extractRegex = new RegExp('hello','g');
let output = extractString.match(extractRegex);
console.log(output);
            

[ 'hello', 'hello' ]
            
multiple matches with case insestivity.

let starString = 'Twinkle twinkle little star';
let starRegex = new RegExp('twinkle','ig');
const starResult = starString.match(starRegex);
console.log(starResult);
            

[ 'Twinkle', 'twinkle' ]
            
The dot/period (.) is a wildcard character used for pattern matching.

let huString = 'hum, hug';
let huRegex = /hu./g
const huresult = huString.match(huRegex);
console.log(huresult);

let unString = 'fun, run';
let unRegex = /.un/g
const unresult = unString.match(unRegex);
console.log(unresult);
            

[ 'hum', 'hug' ]
[ 'fun', 'run' ]
            
The period (.) matches with any of the character but we can also provide a group of character to match as follows.

let vowelString = 'hey there, Are you fine ?'
let vowelRegex = /./g;
let vowelResult = vowelString.match(vowelRegex);
console.log(vowelResult);

vowelString = 'hey there, Are you fine ?'
vowelRegex = /[aeiou]/gi;
vowelResult = vowelString.match(vowelRegex);
console.log(vowelResult);
            

[
'h', 'e', 'y', ' ', 't', 'h',
'e', 'r', 'e', ',', ' ', 'A',
'r', 'e', ' ', 'y', 'o', 'u',
' ', 'f', 'i', 'n', 'e', ' ',
'?'
]
[
'e', 'e', 'e',
'A', 'e', 'o',
'u', 'i', 'e'
]
            
Check for the character in some range using - between the min and max.

let fullSentence = 'The quick brown fox jumps over the lazy dog';
let alphabetRegex = /[a-z]/gi;
const alphabetResult = fullSentence.match(alphabetRegex);
console.log(alphabetResult);
            

[
'T', 'h', 'e', 'q', 'u', 'i', 'c',
'k', 'b', 'r', 'o', 'w', 'n', 'f',
'o', 'x', 'j', 'u', 'm', 'p', 's',
'o', 'v', 'e', 'r', 't', 'h', 'e',
'l', 'a', 'z', 'y', 'd', 'o', 'g'
]
            
Match numbers and letters in a range.

let alphabetsAndNumberString = 'The blueberry pie 3.145672809 is delicious.'
let alphabetsAndNumberRegex = /[2-6h-u]/gi;
const alphabetsAndNumberResult = alphabetsAndNumberString.match(alphabetsAndNumberRegex);
console.log(alphabetsAndNumberResult);
            

[
'T', 'h', 'l', 'u', 'r',
'r', 'p', 'i', '3', '4',
'5', '6', '2', 'i', 's',
'l', 'i', 'i', 'o', 'u',
's'
]
            
Matching all except some using ^ character.

let exceptNumbersStrig = '1234567 hello there, 3 peoples are chasing me! '
let exceptNumbersRegex = /[^0-9]/gi;
const exceptNumbersResult = exceptNumbersStrig.match(exceptNumbersRegex);
console.log(exceptNumbersResult);
            

[
'T', 'h', 'l', 'u', 'r',
'r', 'p', 'i', '3', '4',
'5', '6', '2', 'i', 's',
'l', 'i', 'i', 'o', 'u',
's'
]
            
Match characters that ocuurs one or more times.

let difficultString = 'Mississippi';
let difficultRegex = /s+/ig;
const difficultResult = difficultString.match(difficultRegex);
console.log(difficultResult);
            

[ 'ss', 'ss' ]
            
Match zero or more times.

let zeroOrMoreString = 'GooooooooooooooalGoooooooooalG';
let zeroOrMoreRegex = /Go*/g;
const zeroOrMoreResult = zeroOrMoreString.match(zeroOrMoreRegex);
console.log(zeroOrMoreResult);
            

[ 'Goooooooooooooo', 'Gooooooooo', 'G' ]
            
Find characters with the lazy matching. Which finds the smallest length match.

let lazyString = 'titanic';
let lazyRegex = /t[a-z]*?i/
let lazyResult = lazyString.match(lazyRegex);
console.log(lazyResult);
            

[ 'ti', index: 0, input: 'titanic', groups: undefined ]
            
Find characters with the Greedy matching. Which finds the largest length match.

let greedyString = 'titanic';
let greedyRegex = /t[a-z]*i/
let greedyResult = greedyString.match(greedyRegex);
console.log(greedyResult);
            

[ 'titani', index: 0, input: 'titanic', groups: undefined ]
            
If we applied g flag in the greedy match then it returns all the match except that of the greedy one, And also if there are two matches and starting or ending at the same place then the smaller length one will be cosidered.

let greedyString = 'titanic';
let greedyRegex = /t[a-z]*i/g
let greedyResult = greedyString.match(greedyRegex);
console.log(greedyResult);
            

[ 'ti', 'tani' ]
            
Greedy matching Example...

let htmlString = '

Hello there, I am glad here.

'; let htmlRegex = /<.*>/g; const htmlResult = htmlString.match(htmlRegex); console.log(htmlResult);

[ '<h1>Hello there, I am glad here.</h1>' ]
            
Lazy matching Example...

let htmlString = '

Hello there, I am glad here.

'; let htmlRegex = /<.*?>/g; const htmlResult = htmlString.match(htmlRegex); console.log(htmlResult);

[ '<h1>', '</h1>' ]
            
Checking if a string starts with a given word or not.

let beginString = 'Hey there, I am fine here.';
let beginRegex = /^Hey/;
const beginResult = beginRegex.test(beginString);
console.log(beginResult);
            

true
            
Checking if a string ends with a given word or not.

let endString = 'Hey there, I am fine here.';
let endRegex = /here.$/;
const endResult = endRegex.test(endString);
console.log(endResult);
            

true
            
Match all letters, numbers and an underscore i.e. [A-Z],[a-z],[0-9], and _

let wString = 'Aquick brown fox jumps over a lazy dog with 5_________'
let wRegex = /\w/g;
let wResult = wString.match(wRegex);
console.log(wResult);
            

[
'A', 'q', 'u', 'i', 'c', 'k', 'b', 'r',
'o', 'w', 'n', 'f', 'o', 'x', 'j', 'u',
'm', 'p', 's', 'o', 'v', 'e', 'r', 'a',
'l', 'a', 'z', 'y', 'd', 'o', 'g', 'w',
'i', 't', 'h', '5', '_', '_', '_', '_',
'_', '_', '_', '_', '_'
]
            
Match all except letters, numbers and an underscore i.e. except [A-Z],[a-z],[0-9], and _

let W_String = 'Aquick brown fox jumps over a lazy dog with 5_________'
let W_Regex = /\W/g;
let W_Result = W_String.match(W_Regex);
console.log(W_Result);
            

[
' ', ' ', ' ',
' ', ' ', ' ',
' ', ' ', ' '
]
            
Match all numbers using a shorthand \d

let digitString = '1234567890_abcgsfs'
let digitRegex = /\d/g;
let digitResult = digitString.match(digitRegex);
console.log(digitResult);
            

[
'1', '2', '3', '4',
'5', '6', '7', '8',
'9', '0'
]
            
Match all non-numbers using a shorthand notaion \D

let nonDigitString = '1234567890_abcgsfs'
let nonDigitRegex = /\D/g;
let nonDigitResult = nonDigitString.match(nonDigitRegex);
console.log(nonDigitResult);
            

[
'_', 'a', 'b',
'c', 'g', 's',
'f', 's'
]
            
Q. you are given with a username, and some conditions, you have to tell whether that username satisfies the given conditions.

/*
The conditions are :
1. If there are numbers they must be at the end.
2. Letters can be uppercase or lowercase.
3. Atleast two letters long. Two letters long can't contain the digits.
*/
let userName = 'jackandMeHave12345';
let userCheckRegex = /[a-zA-Z]{2,}\d*$/g;
let result = userCheckRegex.test(userName);
console.log(result);
            

true
            
Match the whitespaces characters i.e the space, tab, newline, etc.

let whitespaceString = 'I am happy now. \n what you want there';
let whitespaceRegex = /\s/g;
let whitespaceResult = whitespaceString.match(whitespaceRegex);
console.log(whitespaceResult);
            

[
' ', ' ', ' ', ' ',
' ', ' ', ' ', '\n',
' ', ' ', ' ', ' '
]
            
Match all non-whitespaces characters.

let nonWhitespaceString = 'I am happy now. \n what you want there';
let nonWhitespaceRegex = /\S/g;
let nonWhitespaceResult = nonWhitespaceString.match(nonWhitespaceRegex);
console.log(nonWhitespaceResult);
            

[
'I', 'a', 'm', 'h', 'a', 'p',
'p', 'y', 'n', 'o', 'w', '.',
'w', 'h', 'a', 't', 'y', 'o',
'u', 'w', 'a', 'n', 't', 't',
'h', 'e', 'r', 'e'
]
            
Quantity specifiers areusedto match some characters with their number and for this we use {a,b} where a is min and b is max.

let quantityString = 'ohhhhhhhhhhhh no, are you mad. ohhhh ';
let quantityRegex = /oh{3,5}/g;
let quantityResult = quantityString.match(quantityRegex);
console.log(quantityResult);
            

[ 'ohhhhh', 'ohhhh' ]
            
Exact number of matches using {x} where x is count of number.

let quantityString = 'ohhhhhhhhhhhh no, are you mad. ohhhh ';
let quantityRegex = /oh{4}/g;
let quantityResult = quantityString.match(quantityRegex);
console.log(quantityResult);
            

[ 'ohhhh', 'ohhhh' ]
            
check with some optional characters using ? after the characters

let optionalString = 'favorite, favourite';
let optionalRegex = /favou?rite/g;
let optionalResult = optionalString.match(optionalRegex);
console.log(optionalResult);
            

[ 'favorite', 'favourite' ]
            
Positive and negative look aheads using (?=someCharacter) and (?=someCharacter)

let lookAheadString = 'quitquit';
let lookAheadPositiveRegex = /qu(?=i)/g;
let lookAheadResult = lookAheadString.match(lookAheadPositiveRegex);
console.log(lookAheadResult);

let lookAheadNegativeRegex = /qu(?!i)/g;
lookAheadResult = lookAheadString.match(lookAheadNegativeRegex);
console.log(lookAheadResult);
            

[ 'qu', 'qu' ]
null